package com.myapp;

import com.gitee.fastmybatis.core.Fastmybatis;
import com.gitee.fastmybatis.core.ext.Mappers;
import com.myapp.dao.TUserMapper;
import com.myapp.entity.TUser;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.MultiMap;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;

public class MainVerticle extends AbstractVerticle {

  @Override
  public void start(Promise<Void> startPromise) throws Exception {

    // 启动加载
    Fastmybatis.create()
      // 指定mybatis-config.xml文件classpath路径
      .configLocation("mybatis/mybatis-config.xml")
      // 指定mybatis sql文件classpath目录
      .mapperLocations("mybatis/mapper")
      // 指定Mapper接口package
      .basePackage("com.myapp.dao")
      .load();

    // Create a Router
    Router router = Router.router(vertx);

    // 浏览器访问：http://localhost:8888/?name=%E5%BC%A0%E4%B8%89
    // Mount the handler for all incoming requests at every path and HTTP method
    router.route().handler(context -> {
      // Get the address of the request
      String address = context.request().connection().remoteAddress().toString();
      // Get the query parameter "name"
      MultiMap queryParams = context.queryParams();
      String name = queryParams.contains("name") ? queryParams.get("name") : "unknown";
      // Mapper
      TUser user = Mappers.run(TUserMapper.class, mapper -> {
        return mapper.getByColumn("username", name);
      });
      // Write a json response
      context.json(new JsonObject()
        .put("name", user == null ? "not found" : "My name is " + user.getUsername())
      );
    });

    // Create the HTTP server
    vertx.createHttpServer()
      // Handle every request using the router
      .requestHandler(router)
      // Start listening
      .listen(8888)
      // Print the port
      .onSuccess(server ->
        System.out.println(
          "HTTP server started on port " + server.actualPort()
        )
      );
  }
}
